<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
  <meta charset="utf-8">
  <meta name="theme-color" content="#222222">
  <title>WLED Live Preview</title>
  <style>
  body {
    margin: 0;
  }
  #canv {
    background: black;
    filter: brightness(175%);
    width: 100%;
    height: 100%;
    position: absolute;
  }
  </style>
</head>
<body>
  <div id="canv" />
  <script>
    function updatePreview(leds) {
      var str = "linear-gradient(90deg,";
      var len = leds.length;        
      for (i = 2; i < len; i+=3) {
        str += `rgb(${leds[i]},${leds[i+1]},${leds[i+2]})`;
        if (i < len -3) str += ","
      }
      str += ")";
      document.getElementById("canv").style.background = str;
    }

    function getLiveJson(e) {
      try {
        if (toString.call(e.data) === '[object ArrayBuffer]') {
          let leds = new Uint8Array(event.data);
          if (leds[0] != 76) return; //'L'
          updatePreview(leds);
        }
      }
      catch (err) {
        console.error("Peek WS error:",err);
      } 
    }

    var ws;
    try {
      ws = top.window.ws;
    } catch (e) {}
    if (ws && ws.readyState === WebSocket.OPEN) {
      console.info("Peek uses top WS");
      ws.send("{'lv':true}");
    } else {
      console.info("Peek WS opening");
      ws = new WebSocket((window.location.protocol == "https:"?"wss":"ws")+"://"+document.location.host+"/ws");
      ws.onopen = function () {
        console.info("Peek WS open");
        ws.send("{'lv':true}");
      }
    }
    ws.binaryType = "arraybuffer";
    ws.addEventListener('message',getLiveJson);
  </script>
</body>
</html>